package com.mty.cc.controller;


import com.mty.cc.po.Admin;
import com.mty.cc.po.User;
import com.mty.cc.service.AdminService;
import com.mty.cc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * @description: 登录控制层
 * @author: mty
 * @time: 2020/01/18 23:07
 */   
@Controller
@RequestMapping(value = "/index")
public class LoginController {


    @Autowired(required=false)
    private UserService userService;

    @Autowired(required=false)
    private AdminService adminService;

    /*
     * @description:跳转到欢迎页面
     * @author: mty
     */
    @RequestMapping("/welcome")
    public ModelAndView welcome(HttpServletRequest reuqest,  Model model) throws Exception{
        ModelAndView mv = new ModelAndView();
        mv.setViewName("welcome");
        return mv;
    }

    /*
     * @description:用户登录
     * @author: mty
     */
    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest reuqest, Model model) throws Exception{
        ModelAndView mv = new ModelAndView();
        mv.setViewName("common/index");
        return mv;
    }

    /*
     * @description:登录校验
     * @author: mty
     */
    @RequestMapping("/userSubmit/{username}/{password}/{type}")
    @ResponseBody
    public String studentSubmit(@PathVariable("username") String username,@PathVariable("password") String password,@PathVariable("type") String type,HttpServletRequest request) throws Exception{
        HttpSession session = request.getSession();
        ModelAndView modelAndView = new ModelAndView();
        if("01".equals(type)){
            List<User> list = userService.queryByOne(username,password);
            if(list.size()==0) {
                request.setAttribute("msg", "对不起，用户不存在，请重试！");
                return "201";
            }else {
                if(list.size()!=1){
                    request.setAttribute("msg", "数据库错误，请重试！");
                    return "202";
                }else{
                    User user = list.get(0);
                    session.setAttribute("username", user.getUsername());
                    session.setAttribute("type", "01");
                    session.setAttribute("id", user.getId());
                    return "index1";
                }
            }
        }else{
            List<Admin> list = adminService.queryByOne(username,password);
            if(list.size()==0) {
                request.setAttribute("msg", "对不起，用户不存在，请重试！");
                return "201";
            }else {
                if(list.size()!=1){
                    request.setAttribute("msg", "数据库错误，请重试！");
                    return "202";
                }else{
                    Admin admin = list.get(0);
                    session.setAttribute("username", admin.getUsername());
                    session.setAttribute("type", "02");
                    session.setAttribute("id", admin.getId());
                    modelAndView.setViewName("index2");
                    return "index2";
                }
            }
        }



    }

    /*
     * @description:登录
     * @author: mty
     */
    @RequestMapping("/goLogin/{data}")
    public ModelAndView goLogin(@PathVariable("data") String data, HttpServletRequest reuqest, Model model) throws Exception{
        ModelAndView mv = new ModelAndView();
        mv.setViewName(data);
        return mv;
    }


    /*
     * @description:注册
     * @author: mty
     */
    @RequestMapping("/register/{username}/{password}/{type}")
    @ResponseBody
    public String userAdd(@PathVariable("username") String username, @PathVariable("password") String password, @PathVariable("type") String type, Model model, HttpServletRequest request) throws Exception{
        ModelAndView mv = new ModelAndView();
        Map mp = new HashMap();
        if("01".equals(type)){
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            try{
                List<User> list = userService.queryByAll();
                for(int i=0;i<list.size();i++){
                    if(user.getUsername().equals(list.get(i).getUsername())){
                        mp.put("msg","对不起，用户名重复，请重试！");
                        return "201";
                    }
                }
                userService.add(user);
                mp.put("msg","注册成功！");
                mp.put("code",200);
                return "200";
            }catch (Exception e){
                mp.put("msg","注册失败！");
                mp.put("code",201);
                return "202";
            }
        }else{
            Admin admin = new Admin();
            admin.setUsername(username);
            admin.setPassword(password);
            try{
                List<Admin> list = adminService.queryByAll();
                for(int i=0;i<list.size();i++){
                    if(admin.getUsername().equals(list.get(i).getUsername())){
                        mp.put("msg","对不起，用户名重复，请重试！");
                        return "201";
                    }
                }
                adminService.add(admin);
                mp.put("msg","注册成功！");
                mp.put("code",200);
                return "200";
            }catch (Exception e){
                mp.put("msg","注册失败！");
                mp.put("code",201);
                return "202";
            }
        }
    }


    /**
     * 判断是否是手机号
     *
     * @param mobile
     * @return
     */
    public static boolean isMobile(String mobile) {
        String regex = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$";
        Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(mobile);
        return m.matches();
    }


    /*
     * @description: 注册时清空session
     * @author: mty
     */
    @RequestMapping("/reset")
    public String reset(HttpServletRequest request) throws Exception{
        HttpSession session   =   request.getSession();
        session.invalidate();
        return "redirect:/index/login";
    }


    /*
     * @description:查看个人信息
     * @author: mty
     */
    @RequestMapping("/query/{type}")
    public String  userAdd(@PathVariable("type") String type, Model model,HttpServletRequest request) throws Exception{
        HttpSession session = request.getSession();
        String id = session.getAttribute("id").toString();
        if("01".equals(type)){
            User user = userService.queryById(id);
            model.addAttribute("user",user);
            model.addAttribute("type",type);
        }else{
            Admin admin = adminService.queryById(id);
            model.addAttribute("admin",admin);
            model.addAttribute("type",type);
        }
        return "common/query";
    }


    /*
     * @description:更新个人信息
     * @author: mty
     */
    @RequestMapping("/update/{type}")
    public String  update(@PathVariable("type") String type,Model model,HttpServletRequest request) throws Exception{
        HttpSession session = request.getSession();
        String id = session.getAttribute("id").toString();
        if("01".equals(type)){
            User user = userService.queryById(id);
            model.addAttribute("user",user);
            model.addAttribute("type",type);
        }else{
            Admin admin = adminService.queryById(id);
            model.addAttribute("admin",admin);
            model.addAttribute("type",type);
        }
        return "common/update";
    }


    /*
     * @description:更新
     * @author: mty
     */
    @RequestMapping("/updateInfo/{type}")
    @ResponseBody
    public String  updateInfo(@PathVariable("type") String type,Model model,HttpServletRequest request,User user) throws Exception{
        HttpSession session = request.getSession();
        String id = session.getAttribute("id").toString();
        if("01".equals(type)){
            User u = userService.queryById(id);
            if(session.getAttribute("id") == null){
                session.setAttribute("msg", "对不起，请登录！");
                return "202";
            }
            if(!isMobile(user.getPhone())){
                return "204";
            }
            if(!isEmail(user.getEmail())){
                return "205";
            }
            if(user.getPassword().length()<1 || user.getUsername().length()<1){
                return "203";
            }
            if(!u.getPassword().equals(user.getPassword())){
                return "201";
            }
            if(user.getRpassword().length()>0){
                user.setPassword(user.getRpassword());
            }
            userService.update(user);
            return "200";
        }else{
            Admin a = adminService.queryById(id);
            a.setRealname(user.getRealname());
            a.setUsername(user.getUsername());
            a.setPhone(user.getPhone());
            if(session.getAttribute("id") == null){
                session.setAttribute("msg", "对不起，请登录！");
                return "202";
            }
            if(!isMobile(user.getPhone())){
                return "204";
            }
            if(user.getPassword().length()<1 || user.getUsername().length()<1){
                return "203";
            }
            if(!a.getPassword().equals(user.getPassword())){
                return "201";
            }
            if(user.getRpassword().length()>0){
                a.setPassword(user.getRpassword());
            }
            adminService.update(a);
            return "200";
        }

    }


    public boolean isEmail(String string) {
        if (string == null)
            return false;
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p;
        Matcher m;
        p = Pattern.compile(regEx1);
        m = p.matcher(string);
        if (m.matches())
            return true;
        else
            return false;
    }


}